package br.com.rubrol.util;

import javax.faces.context.FacesContext;
import java.util.Locale;
import java.util.ResourceBundle;

public class MessageBundleLoader {

	public static final String MESSAGE_PATH = "br.com.rubrol.resource.messages";

	private static ResourceBundle messages;

	private static void init() {
		Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
		if (locale == null) {
			locale = Locale.ENGLISH;
		}
		messages = ResourceBundle.getBundle(MESSAGE_PATH, locale);
	}

	/**
	 * Gets a string for the given key from this resource bundle or one of its
	 * parents.
	 * 
	 * @param key
	 *            the key for the desired string
	 * @return the string for the given key. If the key string value is not
	 *         found the key itself is returned.
	 */
	public static String getMessage(String key) {
		try {
			if (messages == null) {
				init();
			}
			return messages.getString(key);
		}
		// on any failure we just return the key, which should aid in debugging.
		catch (Exception e) {
			return key;
		}
	}
}
